#pragma once

#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <fstream>
#include "util.hpp"
#include <mutex>
namespace ns_index
{

    struct DocInfo
    {
        std::string title;   // 文档标题
        std::string content; // 文档去标签以后的内容
        std::string url;     // 官网文档url
        uint64_t doc_id;     // 文档ID
    };
    // 倒排
    struct InvertedElem
    {
        uint64_t doc_id; // 文档ID
        std::string word;
        int weight;
    };
    // 倒排拉链
    typedef std::vector<InvertedElem> InvertedList;

    class Index
    {
    public:
        ~Index() {}
        // 根据doc_id 找到文档内容
        DocInfo *GetForwardIndex(const uint64_t doc_id)
        {
            if (doc_id >= forward_index.size())
            {
                std::cerr << "doc_id out range ,error" << std::endl;
                return nullptr;
            }
            return &forward_index[doc_id];
        }
        // 根据关键字，获得倒排拉链
        InvertedList *GetInvertedList(const std::string &word)
        {
            auto it = inverted_index.find(word);
            if (it == inverted_index.end())
            {
                std::cerr << "have no InvertedList,error" << std::endl;
                return nullptr;
            }
            return &it->second;
        }
        // date/raw_html/raw.txt
        bool BuildIndex(const std::string &input) // parse 处理完的数据
        {
            std::ifstream in(input, std::ios::in | std::ios::binary);
            if (!in.is_open())
            {
                std::cerr << "sorry,open file " << input << "error" << std::endl;
                return false;
            }
            std::string line;
            int count=0;
            while (getline(in, line))
            {
                DocInfo *doc = BuildForwordIndex(line);
                if (doc == nullptr)
                {
                    std::cerr << "build " << line << " error" << std::endl; // for debug
                    continue;
                }
                BuildInvertedIndex(*doc);
                count++;
                if(count%50==0)
                    LOG(NORMAL,"NOW,已经建立的索引文档："+std::to_string(count));
                    //std::cout<<"NOW,已经建立的索引文档："<<count<<std::endl;
            }
            return true;
        }

    private:
        DocInfo *BuildForwordIndex(std::string line)
        {
            // 解析line line->title content url
            std::vector<std::string> results;
            const std::string sep = "\3"; // 分割符
            ns_util::StringUtil::Split(line, &results, sep);
            if (results.size() != 3)
            {
                return nullptr;
            }
            DocInfo doc;
            doc.title = results[0];
            doc.content = results[1];
            doc.url = results[2];
            doc.doc_id = forward_index.size();
            forward_index.push_back(std::move(doc));
            return &forward_index.back();
        }
        bool BuildInvertedIndex(const DocInfo &doc)
        {
            struct word_cnt
            {
                int title_cnt;
                int content_cnt;
                word_cnt() : title_cnt(0), content_cnt(0) {}
            };
            std::unordered_map<std::string, word_cnt> word_map; // 暂存词频

            std::vector<std::string> title_words;
            ns_util::jiebaUtil::CutString(doc.title, &title_words);

            for (auto e : title_words)
            {
                boost::to_lower(e);
                word_map[e].title_cnt++;
            }

            std::vector<std::string> content_words;
            ns_util::jiebaUtil::CutString(doc.content, &content_words);
            for (auto e : content_words)
            {
                boost::to_lower(e);
                word_map[e].content_cnt++;
            }

#define X 10
#define Y 1
            InvertedElem it;
            for (auto &e : word_map)
            {

                it.doc_id = doc.doc_id;
                it.word = e.first;
                it.weight = e.second.title_cnt * X + e.second.content_cnt * Y; // 临时
                inverted_index[e.first].push_back(std::move(it));
            }
            return true;
        }
        public:
        static Index *GetInstance()
        {
            if (instance == nullptr)
            {
                mtx.lock();
                if (instance == nullptr)
                {
                    instance = new Index();
                }
            }
            mtx.unlock();
            return instance;
        }

    private:
        // 单例
        Index() {}
        Index(const Index &) = delete;
        Index &operator=(const Index &) = delete;
        static Index *instance;
        static std::mutex mtx;

    private:
        // 正排索引可以用数组
        std::vector<DocInfo> forward_index;                           // 正排
        std::unordered_map<std::string, InvertedList> inverted_index; // 倒排
    };
    Index *Index::instance = nullptr;
    std::mutex Index::mtx;
}
